package com.xjl.example.lock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by xiaojinlu1990@163.com on 2019/11/30.
 * CyclicBarrier 可循环调用的方法  重要的方法 （适用场景：用于并行计算）
 * 1 await等待到对应的线程数之后就开始执行剩下的操作
 * 2
 * 3
 *
 */
public class CyclicBarrierExmaple1 {

    private static Logger log = LoggerFactory.getLogger(CyclicBarrierExmaple1.class);

    public final static int clienttotal = 5000;
    public final static int threadTotal = 200;
    public static int count = 0;

    private static Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clienttotal);
        for (int i = 0; i < clienttotal; i++) {

            executor.execute(() ->{
                try {
                    semaphore.release();
                    add();
                    semaphore.acquire();
                }catch (Exception e){
                    log.info("{}",e.getStackTrace());
                }finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        log.info("finish!!!"+count);
        executor.shutdown();
    }

    private static void add() {
        lock.lock();
        count++;
        lock.unlock();
    }


}
